//时间格式化
Date.prototype.format = function(format) {
    var o = {
        "M+" : this.getMonth() + 1,
        "d+" : this.getDate(),
        "h+" : this.getHours(),
        "m+" : this.getMinutes(),
        "s+" : this.getSeconds(),
        "q+" : Math.floor((this.getMonth() + 3) / 3),
        "S" : this.getMilliseconds()
    };
    if (/(y+)/.test(format)){
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o){
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};


/*
 *字符转实体
 *  */
function xssFilter(str)
{
    str = str.replace(/<br\/*>/gi,"");
    str = str.replace(/</gi,'&lt;');
    str = str.replace(/>/gi,'&gt;');

    return str;
}

//字符串截取，中文按照两个
function subString(str, len) {
    var newLength = 0;
    var newStr = "";
    var chineseRegex = /[^\x00-\xff]/g;
    var singleChar = "";
    var strLength = str.replace(chineseRegex,"**").length;
    for(var i = 0;i < strLength;i++) {
        singleChar = str.charAt(i).toString();
        if(singleChar.match(chineseRegex) != null) {
            newLength += 2;
        }else {
            newLength++;
        }
        if(newLength > len) {
            break;
        }
        newStr += singleChar;
    }
    return newStr;
}

//定义剑锋的统计函数之后需要去除掉不应该放在客服模块中
KKCustomerService.statistics = {
    getCkCookie:function(name) {
        var ck = document.cookie.split('; ');
        for (var i = 0; i < ck.length; i++) {
            var c = ck[i].split('=');
            if (name === c[0]) {
                return unescape(c[1]);
            }
        }
    },
    run:function(action,uid){
        var statUrl = "http://inst.stat.chuanke.com/click.html?pid=9";
        $.getScript(statUrl+"&position="+action+"&uv="+this.getCkCookie('_ck_uName')+"&uid="+uid);
    },
    click:function(uid){
        this.run(0,uid);
    },
    success:function(uid){
        this.run(1,uid);
    },
    fail:function(uid){
        this.run(2,uid);
    }
};

//kk客户端
function KKCustomerService(ts,token,CurrentUserInfo){

    //目前而已已经不需要验证了所以我们可以直接传任意的字符串
    if(ts == null){
        ts = 1430297695;
        token = "5426dec35ff8365c976b6a08bf884894";
    }

    //初始化css，加载用到的css
    var cssLoad  = false;
    this.initCss = function(){
        var filename='http://res.ckimg.com/sites/www/v2/css/kkwebtalk.css';
        var linkEl=$("<link/>");
        linkEl.attr("rel", "stylesheet");
        linkEl.attr("type", "text/css");
        linkEl.attr("href", filename);
        $('head').append(linkEl);
        cssLoad = true;
        return this;
    };

    //正在连接的id这个是做啥的？
    var connectingId = null;
    var htmlLoad = false;
    var KKinited = false;
    var flashLogin = false;
    var toClickBtn = null;
    this.isKKinited = function(){
        return KKinited;
    };

    var isPcLogin = false;
    var isPhoneLogin = false;
    var isFlashLogin = false;

    var login_url = (function() {
            var login_url = location.href;
            login_url = KK.base64_encode(login_url);
            login_url = login_url.replace(/\//, '_');
            login_url = "http://passport.chuanke.com/login/index/ret/" + login_url;
            return login_url;
        })();

    var is1v1 = false;

    this.setStyle1v1 = function(){
        is1v1 = true;
        return this;
    };

    this.setStyleDefault = function(){
        is1v1 = false;
        return this;
    };

    var keydownBound = false;
    var initSender = false;
    var initUploader = false;

    //首先载入css和html
    var preSendMsgBox;
    var chatWindow;
    var userid = 0;
    var username;
    //clockId定时用的暂时用不到先屏蔽
    //var clockId;
    //表情包
    var emote = {0: "moren/weixiao.gif", 1: "moren/cry.gif", 2: "moren/bishi.gif", 3: "moren/bukaixin.gif", 4: "moren/buxie.gif", 5: "moren/dai.gif", 6: "moren/fendou.gif", 7: "moren/haha.gif", 8: "moren/haixiu.gif", 9: "moren/han.gif", 10: "moren/qiaoda.gif", 11: "moren/se.gif", 12: "moren/koushui.gif", 13: "moren/kaixin.gif", 14: "moren/nanguo.gif", 15: "moren/qinqin.gif", 16: "moren/huaixiao.gif", 17: "moren/shengqi.gif", 18: "moren/shuijiao.gif", 19: "moren/deyi.gif", 20: "moren/tiaopi.gif", 21: "moren/touxiao.gif", 22: "moren/zaijian.gif", 23: "moren/yiwen.gif", 24: "moren/yun.gif", 25: "moren/hanleng.gif", 26: "moren/kongbu.gif", 27: "moren/kouzhao.gif", 28: "moren/mimi.gif", 29: "moren/wunai.gif", 30: "moren/kulou.gif", 31: "moren/hua.gif", 32: "moren/diaoxie.gif", 33: "moren/xin.gif", 34: "moren/xinsui.gif", 35: "moren/bang.gif", 36: "moren/guzhang.gif", 37: "moren/hecai.gif", 38: "moren/biji.gif", 39: "moren/bookbag.gif", 40: "moren/dengpao.gif", 41: "moren/beer.gif", 42: "moren/tea.gif", 43: "moren/miantiao.gif", 44: "moren/cake.gif", 45: "moren/xigua.gif", 46: "moren/present.gif", 47: "moren/sun.gif", 48: "moren/moon.gif", 49: "moren/star.gif", 50: "moren/flash.gif", 51: "moren/rain.gif", 52: "haitun/weixiao.gif", 53: "haitun/cry.gif", 54: "haitun/bishi.gif", 55: "haitun/bukaixin.gif", 56: "haitun/buxie.gif", 57: "haitun/dai.gif", 58: "haitun/fendou.gif", 59: "haitun/haha.gif", 60: "haitun/haixiu.gif", 61: "haitun/han.gif", 62: "haitun/qiaoda.gif", 63: "haitun/se.gif", 64: "haitun/koushui.gif", 65: "haitun/kaixin.gif", 66: "haitun/nanguo.gif", 67: "haitun/qinqin.gif", 68: "haitun/huaixiao.gif", 69: "haitun/shengqi.gif", 70: "haitun/shuijiao.gif", 71: "haitun/deyi.gif", 72: "haitun/tiaopi.gif", 73: "haitun/touxiao.gif", 74: "haitun/zaijian.gif", 75: "haitun/yiwen.gif", 76: "haitun/yun.gif"};
    //当前的学校ID，估计会修改@todo
    var currentSID;
    //当前的课程ID，默认为0 估计会修改@todo
    var currentCourseID = 0;
    var currentContactEl = null;
    var isMsgOpenBind = false;

    this.setCurrentSID = function(SID){
        currentSID = SID;
    };

    this.setCurrentCourseID = function(CID){
        currentCourseID = CID;
    };

    this.getCurrentCourseID = function(){
        return currentCourseID;
    };

    this.getCustomerService = function(sid){
        //首先判断sid是否在列表中如果不在追加进去
        //实际上点击列表的时候可以不做这个判断之后再修改
        prependContact(sid);
        flashObj("webKK").getCustomerService({sid:parseInt(sid),courseID:parseInt(currentCourseID)});
        //调用之前readycallback的回调方法
    };

    //对方是否在线
    var online = false;
    //对方的客服id，这一版本将会删掉
    var currentServiceID;
    //闭包this
    var self = this;
    //默认的错误图片
    var errorSrc = "http://res.ckimg.com/sites/www/v2/images/public/download_fail2.png";
    //联系人列表
    var contacts = [];
    //当前联系人
    var currentContact = null;

    //获得flash对象的私有方法
    var flashObj = function (movieName){
        if (window.document[movieName]) {
            return window.document[movieName];
        }
        if (navigator.appName.indexOf("Microsoft Internet") == -1) {
            if (document.embeds && document.embeds[movieName])
                return document.embeds[movieName];
        }
        else {
            return document.getElementById(movieName);
        }
    };

    //测试
    window.flashObj = flashObj;

    //uid和uname的一个映射表
    var userNames = function(){
        var names = {};
        var currentNames;

        if(!CurrentUserInfo){
            $.ajax({
                url : '/?mod=ajax&act=customerService&do=getCurrentUserName',
                cache : false,
                async : false,
                type : "GET",
                dataType : 'json',
                success : function (result){
                    currentNames = result
                }
            });
        }else{
            currentNames = CurrentUserInfo;
        }

        names[currentNames.UID] = currentNames;
        //本来是要预先初始化的
        userid = currentNames.UID;
        username = currentNames.UserName;
        return names;
    }();

    //图片点击事件
    var showPic = function(self){
        if(self.attr('src') == errorSrc){
            var realSrc = self.attr('data-realsrc');
            self.attr('src',realSrc);
            return;
        }
        var src = self.attr('src');
        $.ckBoxy({
            width:'600',
            height:'500',
            title:"",
            content:'<img  style="max-width:100%;max-height:440px;display:block;margin:auto auto" src="'+src+'"'
        })
    };

    //根据用户id获得uname
    var getUserNames = function(id){
        //没有登录单独处理
        if(userid == 0 && id != currentServiceID){
            return {NickName:'游客'};
        }

        id = parseInt(id);
        if(!userNames[id]){
            var names;
            $.ajax({
                url : '/?mod=ajax&act=customerService&do=getUserName&UID='+id,
                cache : false,
                async : false,
                type : "GET",
                dataType : 'json',
                success : function (result){
                    names = result
                }
            });
            userNames[id] = names;
        }
        return userNames[id];
    };

    //获得客服头像，暂时没有用处
    /*        var getCustomerServiceAvatar = function(UID){
     var avatar = null;
     $.ajax({
     url : '/?mod=ajax&act=customerService&do=getAvatar&UID='+UID,
     cache : false,
     async : false,
     type : "GET",
     dataType : 'json',
     success : function (data){
     if(data.res){
     avatar = data.url;
     }else{
     avatar = '';
     }
     }
     });
     return avatar;
     };*/

    var getImg = function(name,url,width){
        return "<img id='"+name+"' data-bind='0' src='"+url+"' style='max-width:"+width+"'>";
    };

    var getRealImgPath = function(name){
        return  "http://up.img.chuanke.com/cf/" + name.substr(0, 1) + "/" + name.substr(1, 2) + "/" + name.substr(3, 2) + "/" + name.substr(0,32);
    };

    var getRealMessage = function (message){

        //表情替换
        var regEmote = /\[Emote\:\{(\d+)\}\]/g;
        message = message.replace(regEmote,function(match,id){
            id = id - 1;
            var src = "http://res.ckimg.com/sites/www/v2/images/assets/"+emote[id];
            return "<img src='"+src+"'>";
        });

        //图片替换
        var regImg = /\[Image\:\{(.+)\}\]/g;
        message = message.replace(regImg,function(match,name){
            var src = getRealImgPath(name);
            return "<img data-bind='0' style='max-width:150px' id="+name+" src='"+src+"'>";
        });
        return message;
    };

    //图片click分两种形式绑定 1是error的时候 2是非error的时候同一图片绑定了error就不可绑定非error事件了
    //貌似这里上面的逻辑由于需求变动而作废了
    var getMessageTpl = function (isSelf,nikeName,messageText,time,fromGetList){
        var chatItemHtml =  '<div class="im-bd-chat"><div class="chatitem self">'+
            '<div class="name"><span class="nikeName"></span><span class="time"></span></div>'+
            '<div class="text"></div>'+
            '</div></div>';

        var message = $(chatItemHtml);
        if(!isSelf){
            message.find('.chatitem').removeClass('self');
        }
        message.find('.nikeName').text(nikeName);
        if(!time){
            message.find('.time').text(new Date().format("hh:mm:ss"));
        }else{
            message.find('.time').text(new Date(time*1000).format("hh:mm:ss"));
        }

        message.find('.text').html(getRealMessage(messageText));


        if(!fromGetList){
            //绑定事件
            message.find('img').error(function(){
                var realSrc = $(this).attr('src');
                $(this).attr('data-realsrc',realSrc);
                $(this).attr('src',errorSrc);
            });

            message.find('img[data-bind="0"]').click(function(){
                var self = $(this);
                showPic(self);
            }).attr("data-bind",'1');
        }


        return message;
    };

    //暂时用不到先屏蔽掉
    /*        var listenCustomer = function(){
     clockId = setTimeout(function(){
     if(!chatWindow.children().last().hasClass('customerBusy') && online){
     var busyNotice = $('<div class="customerBusy im-bd-tips">客服忙碌中，您发送的信息会送达当前客服，请耐心等待</div>');
     chatWindow.append(busyNotice);
     }
     },120000);
     };*/

    var flashVar = {};

    var initFlashEl = function(ts,token,UID,username){
        var navigatorName = "Microsoft Internet Explorer";
        var isIE = false;
        var flashEl;
        if( navigator.appName == navigatorName ){
            isIE = true;
        }

        flashVar =
        {
            uid:UID,
            username:username,
            token:token,
            ts:ts,
            readyCallback:"readyCallback",
            failCallback :"failCallback",
            messageCallback:"messageCallback",
            messageListCallback:"messageListCallback",
            contactCallback:"contactCallback",
            customerServiceListCallback:"customerServiceListCallback",
            customerServiceCallback:"customerServiceCallback"
        };

        var flashvarsStr = "";

        for( var key in flashVar){
            flashvarsStr += "&"+key+"="+flashVar[key];
        }

        flashvarsStr = flashvarsStr.substr(1);

        if(isIE){
            flashEl = '<object width="10" height="10" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="webKK" id="webKK">'+
            '<param name="movie" value="http://webkk.chuanke.com/customerService/CustomerService.swf" />'+
            '<param value="'+flashvarsStr+'" name="flashvars">'+
            '<param name="allowScriptAccess" value="always" />'+
            '</object>';
        }else{
            flashEl = '<object width="10" height="10" data="http://webkk.chuanke.com/customerService/CustomerService.swf" name="webKK" type="application/x-shockwave-flash" id="webKK">'+
            '<param value="'+flashvarsStr+'" name="flashvars">'+
            '<param name="allowScriptAccess" value="always" />'+
            '</object>';
        }

        $('body').append(flashEl);
    };

    //记录学校的信息,放在cookie中吧，以免坑爹的跨页面，但是那个schoollnfo怎么办？也改为cookie中么？
    //会不会超限制？
    //信息包括 未读消息数

    var  getCookie = function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') {
                c = c.substring(1,c.length);
            }
            if (c.indexOf(nameEQ) == 0) {
                return unescape(c.substring(nameEQ.length,c.length));
            }
        }
        return false;
    };


    //清除cookie
    var clearCookie = function(name) {
        setCookie(name, "", -1);
    };

    //设置cookie
    var setCookie = function(name, value, seconds) {
        seconds = seconds || 0;
        var expires = "";
        if (seconds != 0 ) {
            var date = new Date();
            date.setTime(date.getTime()+(seconds*1000));
            expires = "; expires="+date.toGMTString();
        }
        document.cookie = name+"="+escape(value)+expires+"; path=/";
    };

    var getSchoolMsgStorage = function(){
        if(!getCookie("SchoolStorage")){
            setCookie("SchoolStorage",JSON.stringify({}))
        }
        return JSON.parse(getCookie("SchoolStorage"));
    };

    var editSchoolMsgStorage = function(value){
        setCookie("SchoolStorage",JSON.stringify(value));
    };

    //消息条数自增
    var schoolMsgStorageIncr = function(SID){
        var msgCount = getSchoolMsgStorage();
        if(SID.toString() in msgCount){
            msgCount[SID] ++;
        }else{
            msgCount[SID] = 1;
        }
        editSchoolMsgStorage(msgCount);
    };


    this.clearSchoolMsgStorage = function(){
        clearCookie("SchoolStorage");
        //清空后标识也去掉
        $("#customerService").find("i").removeClass("hint");
    };

    var currentAnswer;

    var linkToA = function(str){
        var reg = new RegExp("(http://[A-Za-z0-9\\.\\/=\\?%\\-\\_\\&~`@':+!(^\\<)]+)","gm");
        return str.replace(reg,'<a href="$1" target="_blank">$1</a>');
    };

    var createAnswerEl = function(question,answer){
            var html = '<div class="im-bd-chat">\
                        <div class="chatitem">\
                        <div class="text" style="padding-left: 0;padding-right: 0;">\
                                <span class="c_999">[问题]</span>\
                        <span class="myQuestion">sdfdsofds fojds 到底佛顶山的搜房抖擞反倒是</span>\
                        </div>\
                        </div>\
                        <div class="chatitem">\
                        <div class="text" style="padding-left: 0;padding-right: 0;">\
                        <span class="c_999">[答案]</span>\
                        <span class="myAnswer">sdfdsofds fojds 到底佛顶山的搜房抖擞反倒是</span>\
                        </div>\
                        </div>\
                        </div>';
            var item = $(html);
            item.find(".myQuestion").html(question);
            item.find(".myAnswer").html(answer);

            return item;
    };

    var createContactEl = function(SID){

        var html = '<div class="item" style="cursor: pointer">\
                        <div class="photo">\
                        <img class="schoolLogo" src="http://res.ckimg.com/sites/www/v2/images/public/pic_4_3.jpg" width="30" height="30" alt=""/>\
                        </div>\
                        <div class="name schoolName">xxx</div>\
                        <div class="date" style="display: none">03-12</div>\
                        <div class="num MsgCount" data-num="0" style="display: none">0</div>\
                        </div>';
        var EL = $(html);
        //防止不符合的sid进入
        if(!SID) return false;
        if(! (SID in schoolInfoStorage)) return false;
        var schoolInfo = schoolInfoStorage[SID];

        EL.find(".schoolLogo").attr("src",schoolInfo['logo']);
        if(schoolInfo['SchoolName'] == null){
            schoolInfo['SchoolName'] = "";
        }
        EL.find(".schoolName").html(subString(schoolInfo['SchoolName'],10));
        //设置schoolid和customerid
        EL.attr("id","contact"+SID);
        EL.attr("data-schoolId",SID);
        //初始化客服id以后获取客服后修改
        EL.attr("data-serviceId",0);

        //需要绑定点击事件
        EL.click(function(){
            EL.siblings().removeClass("here");
            EL.addClass("here");
            //var autoGetMsgCount = 0;
            //autoGetMsgCount = getMsgCountFromContactEl($(this));
            currentSID = parseInt(EL.attr("data-schoolId"));
            currentContactEl = $(this);
            //调用一下获取客服
            self.getCustomerService(currentSID);
        });

        return EL;
    };

    var contactInList = function(SID){
        return $("#contact"+SID).length;
    };

    var getContactEL = function(SID){
        return $("#contact"+SID);
    };

    var getMsgCountFromContactEl = function(targetContact){
        var currMsgCount = targetContact.find(".MsgCount").attr("data-num");
        if(currMsgCount == ""){
            currMsgCount = 0;
        }else{
            currMsgCount = parseInt(currMsgCount);
        }
        return currMsgCount;
    };

    var contactMsgCountIncr = function(SID,STEP){
        var targetContact = $("#contact" + SID);
        currMsgCount = getMsgCountFromContactEl(targetContact);
        var numBox = targetContact.find(".MsgCount");
        var num = parseInt(numBox.attr("data-num"));
        num = num + STEP;
        numBox.attr("data-num",num);
        if(num > 9) num = "...";
        targetContact.find(".MsgCount").show().text(num);
    };

    var contactMsgCountClear = function(SID){
        var targetContact = $("#contact" + SID);
        targetContact.find(".MsgCount").attr("data-num",0).hide().text(0);
    };

    var createContactEls = function(SIDS){

        getSchoolInfo(SIDS);

        var ELS = [];

        var SID_ARR = SIDS.split(",");

        for(var i = 0; i < SID_ARR.length; i++){
            ELS[ELS.length] = createContactEl(SID_ARR[i]);
        }

        return ELS;
    };

    this.contactMsgCountInit = function(){
        //把cookie中的信息和自己的信息累加
        var msgCount = getSchoolMsgStorage();
        for(var SID in msgCount){
            //如果没有当前学校就建立
            prependContact(parseInt(SID));
            //增加操作
            contactMsgCountIncr(SID,parseInt(msgCount[SID]));
        }
    };

    var schoolInfoStorage = {};

    var prependContact = function(SID){
        if(!contactInList(SID)){
            //首先跟新一下学校storage
            getSchoolInfo(SID);
            var EL = createContactEl(SID);
            if(EL){
                $("#contactList").prepend(EL);
            }
        }
    } ;

    //SID用逗号分开
    var getSchoolInfo = function(SID){

        if(!isNaN(SID)){
            SID = SID.toString();
        }

        SID = SID.split(",");

        //去除已经存在的
        for(var i = 0; i < SID.length; i++){
            if( SID[i] in schoolInfoStorage){
                SID.splice(i,1);
            }
        }

        if(SID.length == 0) return schoolInfoStorage;

        //不存在的重新获取
        SID = SID.join(",");

        $.ajax({
            url : '/?mod=ajax&act=customerService&do=getSchoolInfo&SID='+SID,
            async : false,
            type : "GET",
            dataType : 'json',
            success : function (schoolInfo){
                //无论html是否load都应该初始化
                $.extend(schoolInfoStorage,schoolInfo);
            }
        });

        return schoolInfoStorage;

    } ;

    var initHtml = function (){
        //css
        if(!cssLoad){
            var filename='http://res.ckimg.com/sites/www/v2/css/kkwebtalk.css';
            var linkEl=$("<link/>");
            linkEl.attr("rel", "stylesheet");
            linkEl.attr("type", "text/css");
            linkEl.attr("href", filename);
            $('head').append(linkEl);
            cssLoad = true;
        }

        if(htmlLoad){
            //需要修改@todo
            $("#chatWindow").html('<div class="im-bd-tit" id="connectingBox"><img src="http://res.ckimg.com/sites/www/v2/images/public/loading2.gif" alt=""> 正在为您排队，请稍等...</div>');
            $("#chatClient").show();
            $("#smallChatClient").hide();
        }else{
            //最近联系人和客服之间应该有个对应关系
            var html = '<div class="im-div-wrap" id="chatClient" style="display: none">\
                        <div id="chatWinTop" class="im-contact" style="display: none">\
                        <div class="im-contact-hd">\
                        <h3>最近联系人</h3>\
                        </div>\
                        <div class="im-contact-bd">\
                        <div id="contactList" class="im-contact-list clearfix" style="overflow-y: auto;overflow-x: hidden;height: 339px;">\
                        </div>\
                        </div>\
                        <div class="im-contact-ft"></div>\
                        </div>\
                        <div id="chatWinBottom" class="im-div" style="display: none">\
                        <div class="im-hd">\
                        <div class="im-hd-user">\
                        <div class="photo">\
                        <img class="schoolLogo" id="schoolLogoInWindow" src="" width="30" height="30" alt=""/>\
                        <i id="serviceStatus" class="status offline"></i>\
                        <!--<i class="online"></i>-->\
                        </div>\
                        <span class="name" id="schoolNameInWindow" ></span>\
                        </div>\
                        <div class="im-hd-status">\
                        <a href="javascript:;" class="b" id="toClose"></a>\
                        </div>\
                        </div>\
                        <div class="im-bd" id="chatWindow">\
                        <div class="im-bd-tit" id="connectingBox"><img src="http://res.ckimg.com/sites/www/v2/images/public/loading2.gif" alt=""> 正在为您排队，请稍等...</div>\
                        </div>\
                        <div class="im-ft">\
                        <div class="im-ft-bar">\
                        <a href="javascript:;" class="pictureUpload img" id="kkUploadCover" ></a>\
                        </div>\
                        <div class="im-ft-txt" id="preSendMsgBox" contenteditable="true"><span id="inputTips" class="tips">点击Enter可以直接发送</span></div>\
                        <div class="im-ft-btn">\
                        <a href="javascript:;" class="enter" id="msgSendBtn"></a>\
                        </div>\
                        </div>\
                        </div>\
                        </div>';

            //最小化tpl
            var miniWindow = '<div id="smallChatClient" class="r-msg" style="position:fixed;bottom:1px;right:10px;">\
                           <img src="" width="24" height="24" alt="" class="user">\
                           <span class="txt">与“<span class="schoolName"></span>”聊天中...</span>\
                           </div>';

            var windowEl = $(html);
            var body = $('body');
            body.append(windowEl);

            miniWindow = $(miniWindow);
            body.append(miniWindow);
            miniWindow.hide();

            htmlLoad = true;
        }

        //还要弄个空的好恶心，页面结构设计有瑕疵啊
        var emptyContactTopHtml = '<div class="im-hd" id="emptyContactTop" style="display: none">\
                                        <div class="im-hd-user">\
                                            <h3 class="name" style="text-indent: 20px;">最近联系人</h3>\
                                        </div>\
                                        <div class="im-hd-status">\
                                            <a href="javascript:;" class="b" id="emptyContactCloseBtn"></a>\
                                        </div>\
                                    </div>';

        var emptyContactTopEl = $(emptyContactTopHtml);

        var emptyContactBottomHtml = '<div class="im-empty" id="emptyContactBottom" style="display: none">\
                                       <p><img src="http://res.ckimg.com/sites/www/v2/images/public/im_empty.png" alt=""></p>\
                                       <p class="c_333">您还没有咨询过学校</p>\
                                       <p id="nowLogin" ><a style="color: #066cb8" href="'+login_url+'">现在登录</a> <span class="c_999">保存聊天记录</span></p>\
                                     </div>';

        var emptyContactBottomEl = $(emptyContactBottomHtml);

        //追加进去
        $("#chatClient").append(emptyContactTopEl).append(emptyContactBottomEl);

        //绑定事件
        emptyContactTopEl.find("#emptyContactCloseBtn").click(function(){
            //隐藏chatwindow
            $("#chatClient").hide();
            hideEmptyAndContacts();
        });

        preSendMsgBox = $("#preSendMsgBox");
        chatWindow = $("#chatWindow");

        chatWindow.scroll(function(e){
            e.stopPropagation();
        });

        preSendMsgBox.click(function(){
            $(this).find("#inputTips").remove();
        });
    };

    var hideEmptyShowContacts = function(){
        if(userid > 0) {
            $("#nowLogin").hide();
        }else{
            $("#nowLogin").show();
        }
        $("#emptyContactTop").hide();
        $("#emptyContactBottom").hide();
        $("#chatWinTop").show();
        $("#chatWinBottom").show();
    };

    var hideEmptyAndContacts = function(){
        //根据登录与否判断最后一句话是否要显示
        if(userid > 0) {
            $("#nowLogin").hide();
        }else{
            $("#nowLogin").show();
        }
        $("#emptyContactTop").hide();
        $("#emptyContactBottom").hide();
        $("#chatWinTop").hide();
        $("#chatWinBottom").hide();
    };

    var showEmptyHideContacts = function(){
        if(userid > 0) {
            $("#nowLogin").hide();
        }else{
            $("#nowLogin").show();
        }
        $("#emptyContactTop").show();
        $("#emptyContactBottom").show();
        $("#chatWinTop").hide();
        $("#chatWinBottom").hide();
    };

    //每次获得客服都应该把客服信息放在school里面
    var isWindowOpen = false;

    var msgNotice = $("#customerService");

    var preAnswer = '<span class="c_999">[自动回复] </span>';

    var secondsToHour = function(seconds){
        var ms = seconds / 60;
        var h = ms / 60;
        var m = ms % 60;

        h = h.toString();
        m = m.toString();

        if(h.length == 1){
            h = "0" + h;
        }

        if(m.length == 1){
            m = "0" + m;
        }

        return h+":"+m;
    };

    var openEvBindToDom = false;

    var initFlashCallBack = function (){
        //我们都会尝试去连接客服，只是当用户没有登录的时候连接之后我们不允许发送信息
        window.readyCallback = function(tag){
            //如果是校长或是客服我么需要屏蔽他们的web咨询功能
            if((tag & 8) > 0 || (tag & 1) > 0 ){

            }

            conClosed = false;

            resetMsgNotice();
            //消息通知绑定
            if(isMsgOpenBind == false){
                msgNoticeEventBind();
                isMsgOpenBind = true;
            }

            //鼠标移动自动重新连接
            //autoConBind();
            //连接成功后就可以接受消息了，@todo
            //连接成功后，才让那个东西显示出来是最合理的 @todo
            //获得最近联系人列表，先初始化聊天窗口
            if(!isRefresh){
                //如果是重新登陆的则进行特殊处理,暂时没有什么问题
            }

            flashObj('webKK').getCustomerServiceList();
        };

        window.customerServiceCallback = function(data){

            //当拿到客服的时候
            hideEmptyShowContacts();
            //首先清空掉
            chatWindow.empty();

            //这里面做的事情太多了
            //id, online, info, SID，CourseID ，SchoolName，CustomerStartTime，CustomerEndTime ，IsSetAutoCustomer ，WelcomeSlogan
            data.SID = parseInt(data.SID).toString();

            connectingId = null;

            KKCustomerService.statistics.success(userid);

            var SID = currentSID;
            var  CourseID = currentCourseID;
            //回调成功后把当前课程标识清空
            currentCourseID = 0;

            currentServiceID = parseInt(data.id);
            var tipHtml;
            var isLogin = KK.checkLogin();
            //连接成功有在线离线状态之分

            var serviceStatus = $('#serviceStatus');
            if(data.online == 1){
                //客服在线
                online = true;
                //online
                serviceStatus.removeClass('offline').addClass('online');

                if(isLogin === false){
                    tipHtml = '<div class="im-bd-tit"><i class="im-ok"></i> 客服正在为您服务，<a href="'+login_url+'">登录</a>可查看历史消息。 </div>';
                }else{
                    tipHtml = '<div class="im-bd-tit"><i class="im-ok"></i> 已经成功联系上客服...</div>';
                }
            }else{
                online = false;
                serviceStatus.removeClass('online').addClass('offline');
                //客服不在线

                if(isLogin === false){
                    //当前用户不登陆
                    tipHtml = '<div class="im-bd-tit">' +
                    '</i> <i class="im-error"></i>客服不在线，您可以留言。 <a href="'+login_url+'">登录</a>可更好接收反馈。' +
                    '</div>';
                }else{
                    tipHtml = '<div class="im-bd-tit">' +
                    '</i> <i class="im-error"></i>客服当前不在线，可在线留言，客服之后会回复。' +
                    '</div>';
                }
            }

            $("#connectingBox").remove();

            chatWindow.append(tipHtml);

            //获得更多消息，如果未登录就不展示聊天记录了
            var getMoreMsg = $('<div id="getMore" data-time="0" class="im-bd-tit"><i class="im-more"></i><a href="javascript:;"> 查看更多聊天记录</a></div>');

            if(userid == 0){
                getMoreMsg = $('<div id="getMore" data-time="0" class="im-bd-tit" style="display: none"></div>');
            }

            //如果没有CourseID就不去渲染课程模板
            if(CourseID){
                var url;
                if(is1v1 == false){
                    url = '/?mod=ajax&act=customerService&do=getCourseInfo&CourseID='+CourseID+'&SID='+SID;
                }else{
                    url = '/?mod=ajax&act=customerService&do=get1v1Info&CourseID='+CourseID+'&SID='+SID;
                }
                var courseInfo = function(){
                    var courseInfo = null;
                    $.ajax({
                        url : url,
                        cache : false,
                        async : false,
                        type : "GET",
                        dataType : 'json',
                        success : function (result){
                            courseInfo = result
                        }
                    });
                    return courseInfo;
                }();

                var courseTpl = function(SID,CourseID){
                    var tpl =    '<div class="im-bd-pictxt courseBox"><a href="#" target="_blank">'+
                        '<img src="" width="47" height="35" alt="">'+
                        '<span class="name" ></span><br>'+
                        '<span class="price"></span>'+
                        '</a></div>';
                    var course = $(tpl);

                    if(!is1v1){
                        course.find('a').attr('href','/'+SID+'-'+CourseID+".html");
                    }else{
                        course.find('a').attr('href','/?mod=1v1&act=show&sid='+SID+'&productId='+CourseID);
                    }

                    course.find('img').attr('src',courseInfo.PhotoURL);
                    course.find('.name').text(courseInfo.CourseName);

                    if(!is1v1){
                        course.find('.price').text('￥ '+courseInfo.Cost);
                    }else{
                        course.find('.price').replaceWith("<br/>");
                    }

                    return course;
                }(SID,CourseID);
                chatWindow.append(courseTpl).append(getMoreMsg);
            }else{
                chatWindow.append(getMoreMsg);
            }

            if(online == false){
                //初始化问题列表
                $.getJSON("/?mod=ajax&act=customerQuestion&do=getCustomerQuestions&sid="+currentSID,function(data){
                    //如果没有的话隐藏掉
                    //预留问题应该放在这里奥
                    if(data.length == 0) return;
                    var questionBox = $('<div class="im-bd-guess"><p>您可能遇到的问题:</p><ul class="questionBox" id="questionBox"></ul></div>');
                    chatWindow.append(questionBox);
                    var questionListBox = questionBox.find(".questionBox");
                    for(var i = 0; i < data.length; i++ ){
                        var qInfo = data[i];
                        var qEl = $('<li><span style="cursor: pointer"></span></li>');
                        qEl.find("span").html(linkToA(qInfo["Question"]));
                        qEl.find("a").click(function(e){
                            e.stopPropagation();
                        });
                        qEl.attr("data-id",qInfo["QID"]);
                        questionListBox.append(qEl);
                        //绑定事件
                        qEl.click(function(){
                            var qid = $(this).attr("data-id");
                            var text = $(this).find("span").html();
                            $.getJSON("/?mod=ajax&act=customerQuestion&do=getCustomerQuestionAnswer&sid="+currentSID+"&qid="+qid,function(data){
                                if(!data["Answer"]) return;
                                var autoMessage = createAnswerEl(text,linkToA(data["Answer"]));
                                chatWindow.append(autoMessage).scrollTop(1000000);
                            });
                        });
                    }
                })
            }

            initGetMsgList();

            var names = getUserNames(currentServiceID);
            var autoMessage;
            var pos;
            var num2str = ['周一','周二','周三','周四','周五','周六','周天'];
            pos = data['WelcomeSlogan'].lastIndexOf("||");
            if(online){
                if(data['WelcomeSlogan']){
                    autoMessage = getMessageTpl(false,names.NickName, linkToA(data['WelcomeSlogan'].substr(0,pos)));
                }
            }else{
                if(data['WelcomeSlogan']){
                    var time = parseInt(data['WelcomeSlogan'].substr(pos+2));
                    //显示不在线提醒
                    autoMessage = "抱歉，目前客服不在线，人工服务时间";
                    for(var i=0; i < 7;i++){
                        if((time & Math.pow(2,i)) >= 1){
                            autoMessage += num2str[i] + "、";
                        }
                    }
                    autoMessage = autoMessage.substr(0,autoMessage.length - 1);
                    //时间区间
                    autoMessage += secondsToHour(data["CustomerStartTime"])+"至"+secondsToHour(data["CustomerEndTime"]);

                    autoMessage = getMessageTpl(false,names.NickName, preAnswer + autoMessage);
                }
            }
            chatWindow.append(autoMessage);

            var autoGetMsgCount = getMsgCountFromContactEl(currentContactEl);

            if(autoGetMsgCount > 0){
                flashObj('webKK').getMessageList(currentSID,autoGetMsgCount);
                //把消息通知隐藏掉
                contactMsgCountClear(currentSID);
            }

            //聊天窗口的logo
            var schoolInfo = getSchoolInfo(currentSID)[currentSID];

            $("#schoolLogoInWindow").attr('src',schoolInfo.logo);
            $("#schoolNameInWindow").text(schoolInfo.SchoolName);
        };

        window.customerServiceListCallback = function(data){
            //初始化最近联系人列表
            if(data.length > 0 ){
                var SIDS = [];
                for(var i=0; i< data.length; i++){
                    if(contactInList(data[i].SID)) continue;
                    SIDS[SIDS.length] = data[i].SID;
                }
                var els = createContactEls(SIDS.join(","));
                initContactsList(els);
            }else{
                //最近联系人为空的情况
                //showEmptyHideContacts();
            }

            if(!openEvBindToDom){
                self.bindToDom();
                openEvBindToDom = true;
            }

            //这里是恶心的需求打的补丁
            /***********************************/
            //用于refresh之后的自动点击，后人一定要去掉啊
            /***********************************/
            if(toClickBtn){
                toClickBtn.trigger("click");
                toClickBtn = null;
            }

        };

        window.failCallback = function(data){
            //标注已经断开了
            conClosed = true;

            var ret = checkLogin();
            var isPcLogin = false;
            var isPhoneLogin = false;

            if("LogFrom" in ret.data){

                if(ret.data.LogFrom == 0){
                    isPcLogin = true;
                    isPhoneLogin = false;
                    isFlashLogin = false;
                }

                if( ret.data.LogFrom == 1 || ret.data.LogFrom == 2 || ret.data.LogFrom == 4){
                    isPhoneLogin = true;
                    isPcLogin = false;
                    isFlashLogin = false;
                }

            }


            if(data.code != 9 ){
                KKCustomerService.statistics.fail(userid);
            }

            //console.log("closed!");
            //连接断开的标识现在不需要了
        };

        //收到消息后的处理
        //如果聊天窗口打开了所有的消息通知展示在联系人除，mini窗口将不再有效
        //当前联系人的通知直接以消息方式展示，其他的用未读消息展示
        //打开聊天窗口前，未读消息放在cookie中，打开窗口后初始化未读消息

        window.messageCallback = function(data){
            //fromId sid

            data.fromId = parseInt(data.fromId).toString();
            data.sid = parseInt(data.sid).toString();

            var isSelf = userid == data.fromId ? true:false;

            //为了测试我修改一下之后记得改回来 @todo
            //isSelf = false;
            //isWindowOpen = false;

            var names = getUserNames(data.fromId);
            var message = null;

            if(isWindowOpen){
                //首先看窗口是否打开
                if(isSelf){
                    //如果是当前的用户则把消息添加进去
                    message = getMessageTpl(isSelf,names.NickName,xssFilter(data.message));
                    chatWindow.append(message).scrollTop(1000000);
                }else{
                    //如果不是自己的消息那么离线状态应该修改掉
                    var serviceStatus = $('#serviceStatus');

                    serviceStatus.removeClass('offline').addClass('online');

                    if(data.sid != currentSID){
                        //如果不是自己的信息，则判断是否学习在列表，如果不在放入列表如果在给消息加一
                        prependContact(data.sid);
                        //消息自增1
                        contactMsgCountIncr(data.sid,1);
                    }else{
                        //信息直接append进来
                        message = getMessageTpl(isSelf,names.NickName,xssFilter(data.message));
                        chatWindow.append(message).scrollTop(1000000);
                    }
                }
            }else{
                //窗口如果没有打开，这个地方是最恶心的感觉产品设计完全在yy
                //窗口没有打开的话直接放在cookie中等待第一个打开的聊天窗口去认领消息，然后再清空
                //校长和客服身份的话应该规避掉这个情况
                schoolMsgStorageIncr(data.sid);
                //修改消息通知
                $("#customerService").find("i").addClass("hint");
            }
        };

        window.messageListCallback = function(data){
            var messageList = null;
            var getMoreEL = $("#getMore");
            if(data.length < 1){
                alert("没有更多聊天记录了");
            }
            $(data).each(function(i,item){
                item.fromId = parseInt(item.fromId);

                var isSelf = userid == item.fromId ? true:false;
                var names = getUserNames(item.fromId);
                var htmlBox = $("<div></div>");
                var message = getMessageTpl(isSelf,names.NickName,xssFilter(item.message),item.time,true);
                htmlBox.html(message);
                //当作为html字符串连接的时候原本作为对象绑定的事情就不再有了
                //需要重新绑定，但是通过非getlist获得的又有绑定事件
                //在做html相加的时候htmlBox的已经绑定需要清空
                //var lastTime = getMoreEL.attr('data-time');
                //getMoreEL.attr('data-time',item.time);
                if(messageList == null){
                    messageList = htmlBox.html();
                }else{
                    messageList  = messageList + htmlBox.html();
                }

            });

            getMoreEL.after(messageList);

            chatWindow.find('img[data-bind="0"]').click(function(){
                showPic($(this));
            }).attr('data-bind','1');
        };

        window.contactCallback = function(data){

        }
    };

    var initContactsList = function(els){
        for(var i=0; i<els.length; i++){
            $("#contactList").append(els[i]);
        }
    };

    var initSend = function(){
        var sender = function (){
            $("#inputTips").remove();
            preSendMsgBox.find('div').remove();
            preSendMsgBox.find('img').each(function(i,item){
                var name = $(item).attr('id')+".jpg";
                $(item).replaceWith("[Image:{"+name+"}]")
            });

            var sendData = preSendMsgBox.text();

            if(preSendMsgBox.html() != "") {
                //此处暂且设置为无限大
                //chatWindow.append(message).scrollTop(1000000);
                chatWindow.scrollTop(1000000);
                //var reg = /<br\/{0,1}>/i;
                flashObj('webKK').sendMessage({sid:currentSID,cid:currentServiceID,message:sendData});
            }

            preSendMsgBox.empty();
        };

        $("#msgSendBtn").click(function(e){
            sender();
        });

        //绑定激活按钮
        $("#preSendMsgBox").click(function(){
           //激活本地flash
            if(conClosed){
                self.refresh(flashVar);
                isFlashLogin = true;
                isPcLogin = false;
                isPhoneLogin = false;
            }
        });

        if(!keydownBound){
            $(document).keydown(function(e){
                if(e.keyCode==13){
                    sender();
                }
                //preSendMsgBox.focus();
            });
            keydownBound = true;
        }
    };

    var initUpLoad = function(){
        var uploadUrl = "http://res.ckimg.com/lib/jquery/plugin/jquery.uploadify-3.1.js";
        var initUp= function(){
            $("#kkUploadCover").uploadify3({
                height			:'22',
                swf				: "http://res.ckimg.com"+"/common/v2/swf/uploadify-3.1.swf",
                uploader		: "http://up.img.chuanke.com/cf.php",
                width			: '22',
                buttonCursor	: 'hand',
                buttonClass   : 'pictureUpload',
                buttonText		: "",
                fileObjName	: 'upfile',
                fileSizeLimit	: '2MB',
                fileTypeExts	: '*.jpg;*.png;*.gif;',
                multi:false,

                onSelect : function(fileObj) {
                    this.startUpload();
                },

                onUploadSuccess : function(file, fileName, response) {
                    if(fileName=='error'){
                        //上传失败
                    }else{
                        var img = getImg(fileName,getRealImgPath(fileName),150);
                        //删除默认文案
                        $("#inputTips").remove();
                        preSendMsgBox.append(img);
                    }
                }
            });
        };

        if("uploadify3" in ($.fn)){
            initUp();
        }else{
            jQuery.getScript(uploadUrl,initUp)
        }

    };

    var initGetMsgList = function(){
        chatWindow.find("#getMore").click(function(){
            flashObj('webKK').getMessageList(currentSID,10);
        });
    };

    var initCloseBtn = function(){
        $("#toClose").click(function(){
            //标注已经关闭
            isWindowOpen = false;
            $("#chatClient").hide();
        });
    };

    var msgNoticeEventBind = function(){
        msgNotice.click(function(){
            if(userid > 0 && checkAndSetPhoneOrPcLogin()){
                return;
            }
            isWindowOpen = true;
            //显示client
            $("#chatClient").show();
            self.contactMsgCountInit();
            //自动触发第一个
            if($("#contactList div").length > 0 ){
                $("#contactList div").eq(0).trigger("click");
                //清空未读消息
                self.clearSchoolMsgStorage();
            }else{
                showEmptyHideContacts();
            }
        });
    };

    this.openSchoolWindow = function(SID){
        hideEmptyShowContacts();
        $("#chatClient").show();
        isWindowOpen = true;
        self.contactMsgCountInit();
        //追加学校联系人
        prependContact(SID);
        currentContactEl = getContactEL(SID);
        currentContactEl.trigger("click");
        self.clearSchoolMsgStorage();
    };

    var conClosed = true;

    var autoConBind = function(){
    };


    var  checkLogin = function(){
        var ret;
        $.ajax({
            url:"/?mod=classroom&act=index&do=test",
            type:"get",
            dataType:"json",
            async : false,
            success:function(data){
                ret = data
            }
        });
        return ret;
    };

    var checkPCLogin = function(){
        var ret = checkLogin();
        if("LogFrom" in ret.data){
           if(ret.data.LogFrom == 0){
               return true;
           }
        }
        return false;
    };

    var checkAndSetPhoneOrPcLogin = function(){
        var ret = checkLogin();
        if("LogFrom" in ret.data){
            if(ret.data.LogFrom == 0){
                isPcLogin = true;
                isFlashLogin = false;
                isPhoneLogin = false;
            }else if(ret.data.LogFrom == 1 || ret.data.LogFrom == 2 || ret.data.LogFrom == 4){
                isPhoneLogin = true;
                isPcLogin = false;
                isFlashLogin = false;
            }else{
                isPcLogin = false;
                isPhoneLogin = false;
            }

            if(ret.data.LogFrom == 0 || ret.data.LogFrom == 1 || ret.data.LogFrom == 2 || ret.data.LogFrom == 4){
                return true;
            }
        }
        return false;
    };

    var checkPhoneLogin = function(){
        var ret = checkLogin();
        if(("LogFrom" in ret.data)){
            if( ret.data.LogFrom == 1 || ret.data.LogFrom == 2 || ret.data.LogFrom == 4){
                return true;
            }
        }
        return false;
    };

    this.init = function(){
        //统计点击
        KKCustomerService.statistics.click(userid);

        //这里是个极其恶心人的补丁，产品啊哎
        /*---------------------------------*/
        //初始化的时候检测pc是否登录了如果登录了用户暂时用匿名用户登录
        var userid2 = userid;
        var username2 = username;
        //如果pc移动端有一方登录了，初始化的时候就应该匿名登录
        if(userid > 0){
            if(checkAndSetPhoneOrPcLogin()){
                userid2 = 0;
                username2 = null;
                isFlashLogin = false;
            }else{
                //flash方面要登录了
                isFlashLogin = true;
                isPcLogin = false;
                isPhoneLogin = false;
            }
        }
        /*---------------------------------*/
        initHtml();
        initFlashEl(ts,token,userid2,username2);
        initFlashCallBack();
        initCloseBtn();
        initUpLoad();
        initSend();

        KKinited = true;
    };

    var isRefresh = false;

    var resetMsgNotice = function(){
        var customerService = $("#customerService");
        customerService.find("i").removeClass("hint");
        var schoolMsgCount = getSchoolMsgStorage();
        for(var sid in schoolMsgCount){
            if(schoolMsgCount[sid] > 0){
                customerService.find("i").addClass("hint");
            }
        }
    };

    this.refresh = function(){
        isRefresh = true;
        //如果pc端登陆的话就不去重新连接了

        //如果refresh的话
        resetMsgNotice();
        flashVar.uid = userid;
        flashVar.username = username;
        flashObj('webKK').refresh(flashVar);
    };

    //这是个恶心的补丁恶心啊产品
    //预定点击按钮

    var prepareFlashLogin = false;

    this.bindToDom = function(){

        var jq_verion_number = $.fn.jquery.replace(/\./g, '');

        var callback = function() {

            //这是个恶心的补丁恶心啊产品
            /******************************************/
            var checkPC;

            if(prepareFlashLogin){
                checkPC = false;
                prepareFlashLogin = false;
            }else{
                if(userid > 0){
                    checkAndSetPhoneOrPcLogin();
                    checkPC = isPcLogin;
                }
            }

            if(!isFlashLogin && userid > 0 && !checkPC){
                //flash没有登录，pc端没有登录，userid>0 才要自己刷新flash登录
                toClickBtn = $(this);
                //标注此时是flash登录了
                self.refresh(flashVar);
                isFlashLogin = true;
                isPcLogin = false;
                isPhoneLogin = false;
                prepareFlashLogin = true;
                return;
            }

            /******************************************/

            var sid = $(this).attr('data-sid');
            var courseid = $(this).attr('data-courseid');
            var is1v1 = $(this).attr("data-is1v1");

            if (typeof(courseid) == 'undefined') {
                courseid = 0;
            }

            if(userid > 0 && checkPC){
                //如果用户在线，pc在线，用户点击了按钮就把pc调起来
                window.location = 'chuankekk:t=cs_chat?uid='+userid+'&sid='+sid+'&cousreid='+courseid;
                return;
            }

            if (is1v1 == '1') {
                self.setStyle1v1();
            } else {
                self.setStyleDefault();
            }

            self.setCurrentSID(sid);
            self.setCurrentCourseID(courseid);
            self.openSchoolWindow(sid);
        };


        if(jq_verion_number < 180){
            $(".openChatWindow:not([data-chatbind])").live('click',callback);
        }else{
            $("body").on('click', '.openChatWindow:not([data-chatbind])',callback);
        }
    };

}

//初始化
(function(){
    var cs= new KKCustomerService();
    cs.initCss();
    cs.init();
    //修改一下应该在callback后才可以binddom
    //cs.bindToDom();
})();


